package org.jl.demo.util;

import org.jl.demo.authority.model.bo.Field;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SqlUtil {

    public static String getCountSql(String tableName, int id) {
        return "select count(1) from " + tableName + " where id=?";
    }

    public static String getInsertSql(String tableName, String[] columnStr) {
        return "insert into " + tableName + " (" + columnStr[0] + ") values (" + columnStr[1] + ")";
    }

    public static String[] getInsertColumnStr(Map<String, Object> init) {
        StringBuilder str1 = new StringBuilder();
        StringBuilder str2 = new StringBuilder();
        for (String column : init.keySet()) {
            if (!str1.isEmpty()) {
                str1.append(",");
                str2.append(",");
            }
            str1.append(column);
            str2.append("?");
        }
        return new String[]{str1.toString(), str2.toString()};
    }

    public static Object[] getValues(Map<String, Object> init, Map<String, Field> fieldMap) {
        List<Object> values = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (Map.Entry<String, Object> entry : init.entrySet()) {
            Field field = fieldMap.get(entry.getKey());
            String value = String.valueOf(entry.getValue());
            switch (field.getType()) {
                case "tinyint" -> {
                    if (Integer.valueOf(1).equals(field.getLength())) {
                        values.add(Boolean.valueOf(value));
                    }
                    values.add(Byte.valueOf(value));
                }
                case "integer" -> values.add(Integer.valueOf(value));
                case "bigint" -> values.add(Long.valueOf(value));
                case "decimal" -> values.add(new BigDecimal(value));
                case "datetime" -> values.add(LocalDateTime.parse(value, formatter));
                default -> values.add(value);
            }
        }
        return values.toArray();
    }

}
